﻿using System;
using System.IO;
using System.Windows;
using ImageAppDataModels;
using ImageAppViewModels;
using BrainTechLLC;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static App TheApp;
        public static ICoreDataProvider DataProvider;
        
        public App()
        {
            if (TheApp != null)
            {
                return;
            }

            DataProvider = new DiskDataProvider();

            Startup += new StartupEventHandler(App_Startup);
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);                        
            TheApp = this;
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.Exception.ToString());
        }

        void App_Startup(object sender, StartupEventArgs e)
        {            
            if (DataProvider.Exists(FilePaths._metaDataFilePath))
            {
                DataLoader._metaData = AllMetaData.ReadFromDisk(FilePaths._metaDataFilePath, DataProvider);
            }
            else
            {
                DataLoader._metaData = new AllMetaData();
            }
            Train();
        }

        private double[,] data = null;

        //private int populationSize = 100;
        //private int iterations = 1000;
        //private int selectionMethod = 0;
        //private int functionsSet = 0;
        //private int geneticMethod = 0;

        public void LoadData(string path)
        {
            StreamReader reader = null;
            // read maximum 50 points
            double[,] tempData = new double[50, 2];
            double minX = double.MaxValue;
            double maxX = double.MinValue;

            try
            {
                // open selected file
                reader = File.OpenText(path);
                string str = null;
                int i = 0;

                // read the data
                while ((i < 50) && ((str = reader.ReadLine()) != null))
                {
                    string[] strs = str.Split(';');
                    if (strs.Length == 1)
                        strs = str.Split(',');
                    // parse X
                    tempData[i, 0] = double.Parse(strs[0]);
                    tempData[i, 1] = double.Parse(strs[1]);

                    // search for min value
                    if (tempData[i, 0] < minX)
                        minX = tempData[i, 0];
                    // search for max value
                    if (tempData[i, 0] > maxX)
                        maxX = tempData[i, 0];

                    i++;
                }

                // allocate and set data
                data = new double[i, 2];
                Array.Copy(tempData, 0, data, 0, i * 2);
            }
            catch (Exception)
            {
                //MessageBox.Show( "Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
                return;
            }
            finally
            {
                // close file
                if (reader != null)
                    reader.Close();
            }

        }

        public void Train()
        {
            AllMetaData meta = DataLoader._metaData;

            //LoadData(@"C:\Shared\AForge\aforge-read-only\Samples\Genetic\Approximation\Data Samples\Sample2.csv");
            //// create fitness function
            //SymbolicRegressionFitness fitness = new SymbolicRegressionFitness(data, new double[] { 1, 2, 3, 5, 7 });
            
            //// create gene function
            //IGPGene gene = (functionsSet == 0) ? (IGPGene)new SimpleGeneFunction(6) : (IGPGene)new ExtendedGeneFunction(6);
            //// create population
            //Population population = new Population(populationSize, (geneticMethod == 0) ? (IChromosome)new GPTreeChromosome(gene) : (IChromosome)new GEPChromosome(gene, 15),
            //    fitness, (selectionMethod == 0) ? (ISelectionMethod)new EliteSelection() : (selectionMethod == 1) ? (ISelectionMethod)new RankSelection() : (ISelectionMethod)new RouletteWheelSelection() );

            //int i = 1;
            //double[,] solution = new double[50, 2];
            //double[] input = new double[6] { 0, 1, 2, 3, 5, 7 };

            //while (true)
            //{
            //    population.RunEpoch();

            //    try
            //    {
            //        // get best solution
            //        string bestFunction = population.BestChromosome.ToString();

            //        // calculate best function
            //        for (int j = 0; j < 50; j++)
            //        {
            //            input[0] = solution[j, 0];
            //            solution[j, 1] = PolishExpression.Evaluate(bestFunction, input);
            //        }

            //        // calculate error
            //        double error = 0.0;
            //        for (int j = 0, k = data.GetLength(0); j < k; j++)
            //        {
            //            input[0] = data[j, 0];
            //            error += Math.Abs(data[j, 1] - PolishExpression.Evaluate(bestFunction, input));
            //        }

            //    }
            //    catch
            //    {                    
            //    }

            //    // increase current iteration
            //    i++;

            //    //
            //    if ((iterations != 0) && (i > iterations))
            //        break;
            //}

            //// show solution
            //Console.WriteLine(solution.ToString());
            //Console.WriteLine(population.BestChromosome.ToString());            
        }
    }
}
